<script setup lang="ts">
import { onMounted, ref, reactive, provide } from 'vue'
import LineHeader from '@/components/LineHeader.vue'
import {
  createLogisticsOrder,
  deleteLogisticsOrderById,
  getLogisticsOrderById,
  getLogisticsOrderList,
  getProviderList,
  updateLogisticsOrder,
  deleteLogisticsOrderByIdList,
} from '@/apis/logistics'
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  ElMessageBox,
  type Action,
} from 'element-plus'
import { getOrderList } from '@/apis/order'
import { computed } from 'vue'

/**
 * 物流商订单列表
 */
const orderList = ref()
// 物流商列表
const vendorIDList = ref()
/**
 * 添加物流商订单
 */
// 商品订单列表
const orderIDList = ref()

// 添加物流商订单弹窗
const addOrderFormVisible = ref(false)
// 添加物流商订单表单
const addOrderForm: any = ref({
  OrderID: '',
  VendorID: '',
  Address: '',
  Consignee: '',
  Telephone: '',
  Remarks: '',
})
// 添加表单对象
const addOrderFormRef = ref()
// 打开添加物流商订单弹窗
const openAddOrderForm = () => {
  addOrderFormVisible.value = true
}
// 添加表单校验规则
const orderFormRules = reactive<FormRules>({
  OrderID: [
    {
      required: true,
      message: '请选择订单ID',
      trigger: 'blur',
    },
  ],
  VendorID: [
    {
      required: true,
      message: '请选择物流商',
      trigger: 'blur',
    },
  ],
  Address: [
    {
      required: true,
      message: '请输入收货地址',
      trigger: 'blur',
    },
  ],
  Consignee: [
    {
      required: true,
      message: '请输入收货名',
      trigger: 'blur',
    },
  ],
  Telephone: [
    {
      required: true,
      message: '请输入电话',
      trigger: 'blur',
    },
  ],
  Remarks: [
    {
      required: true,
      message: '请输入物流商订单备注',
      trigger: 'blur',
    },
  ],
})

// 添加物流商订单表单提交
const submitAddOrdersForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('添加物流商订单')
      const res = await createLogisticsOrder(addOrderForm.value)
      if (res.status === 200) {
        ElMessage({
          message: '添加成功',
          type: 'success',
        })
        addOrderFormVisible.value = false
      } else {
        ElMessage({
          message: '添加失败 ' + res.data.error,
          type: 'error',
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

/**
 * 查看物流商订单
 */
const orderInfo = ref()
const checkOrderFormVisible = ref(false)
const handleCheck = async (index: number, row: any) => {
  const res = await getLogisticsOrderById(row.LogisticsID)
  orderInfo.value = res.data
  checkOrderFormVisible.value = true
}

/**
 * 编辑物流商订单
 */
// 打开编辑物流商订单弹窗
const handleEdit = async (index: number, row: any) => {
  editOrderForm.value = { ...row }
  editOrderFormVisible.value = true
  editOrderForm.value.LogisticsID = row.LogisticsID
  console.log(editOrderForm.value)
}

// 编辑物流商订单弹窗
const editOrderFormVisible = ref(false)
// 编辑物流商订单表单
const editOrderForm: any = ref({
  LogisticsID: '',
  OrderID: '',
  VendorID: '',
  Address: '',
  Consignee: '',
  Telephone: '',
  Remarks: '',
})
// 编辑表单对象
const editOrderFormRef = ref()

// 编辑物流商订单表单提交
const submitEditOrdersForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('编辑物流商订单')
      const res = await updateLogisticsOrder(editOrderForm.value.LogisticsID, editOrderForm.value)
      if (res.status === 200) {
        ElMessage({
          message: '编辑成功',
          type: 'success',
        })
        editOrderFormVisible.value = false
        console.log(res)
      } else {
        ElMessage({
          message: '编辑失败',
          type: 'error',
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

/**
 * 删除物流商订单
 */
// 删除物流商订单
const handleDelete = (index: number, row: any) => {
  console.log(index, row)
  ElMessageBox.alert('确认删除 ' + row.LogisticsID + ' 物流商订单？', '删除物流商订单', {
    confirmButtonText: '确认',
    callback: async (action: Action) => {
      if (action === 'confirm') {
        ElMessage({
          type: 'success',
          message: `删除${row.LogisticsID}物流商订单成功`,
        })
        await deleteLogisticsOrderById(row.LogisticsID)

        // 删除 ordersList 中的数据
        orderList.value.splice(index, 1)
      } else {
        ElMessage({
          type: 'error',
          message: `删除${row.LogisticsID}物流商订单失败`,
        })
      }
    },
  })
}

/**
 * 批量删除
 */
/**
 * 获取要删除的列表
 */
type Order = {
  LogisticsID: 0
}
const selectable = (row: Order) => ![-100].includes(row.LogisticsID)
const deleteButtonDisable = computed(() => {
  if (deleteOrderList.value.length === 0) {
    return true
  } else {
    return false
  }
})
const deleteOrderList: any = ref([])
const deleteOrderIdList: any = ref()
const handleSelectionChange = (val: any) => {
  deleteOrderList.value = val
  deleteOrderIdList.value = val.map((item: any) => item.LogisticsID)
  console.log(deleteOrderIdList.value)
}
const handleBatchDelete = () => {
  ElMessageBox.alert('确认删除已选订单？', '删除订单', {
    confirmButtonText: '确认',
    callback: async (action: Action) => {
      if (action === 'confirm') {
        ElMessage({
          type: 'success',
          message: `删除订单成功`,
        })
        await deleteLogisticsOrderByIdList(deleteOrderIdList.value)

        window.location.reload()
      } else {
        ElMessage({
          type: 'error',
          message: `删除订单失败`,
        })
      }
    },
  })
}

// 获取数据
const initOrders = async () => {
  const orders = await getLogisticsOrderList({})
  const pOrders = await getOrderList({ page: 1, size: 1000 })
  const provider = await getProviderList({})
  orderList.value = orders.data
  orderIDList.value = pOrders.data
  vendorIDList.value = provider.data
}

// 初始化
onMounted(async () => {
  await initOrders()
  console.log(orderList.value)
})
</script>
<template>
  <div id="orders">
    <el-container style="height: 100%">
      <el-main>
        <LineHeader #text>物流商订单列表</LineHeader>

        <!-- 头部 -->
        <el-row class="options-row">
          <el-col :span="8"> </el-col>
          <el-col :span="8"> </el-col>
          <el-col :span="8">
            <div class="add">
              <el-button class="add-button" type="primary" @click="openAddOrderForm"
                >添加物流商订单</el-button
              >
              <el-button
                class="delete-button"
                type="danger"
                @click="handleBatchDelete"
                :disabled="deleteButtonDisable"
                >批量删除</el-button
              >
            </div>
          </el-col>
        </el-row>

        <!-- 物流商订单数据 -->
        <el-table
          ref="multipleTableRef"
          :data="orderList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" :selectable="selectable" width="55" />
          <el-table-column label="运单号">
            <template #default="scope">{{ scope.row.LogisticsID }}</template>
          </el-table-column>
          <el-table-column property="VendorID" label="物流商号" />
          <el-table-column property="OrderID" label="订单号" />
          <el-table-column property="Address" label="收货地址" />
          <el-table-column property="Consignee" label="收货名" />
          <el-table-column property="Telephone" label="联系电话" />
          <el-table-column property="Status" label="最新状态" />
          <el-table-column property="Remarks" label="备注" />
          <el-table-column label="操作" width="300px">
            <template #default="scope">
              <el-button type="success" @click="handleCheck(scope.$index, scope.row)">
                查看
              </el-button>
              <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
                编辑
              </el-button>
              <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <!-- 添加物流商订单 -->
    <el-dialog v-model="addOrderFormVisible" title="添加物流商订单" width="800">
      <el-form :model="addOrderForm" ref="addOrderFormRef" :rules="orderFormRules">
        <el-form-item label="商品订单ID" prop="OrderID" label-width="150px">
          <el-select v-model="addOrderForm.OrderID" placeholder="请选择商品订单ID">
            <el-option
              v-for="item in orderIDList"
              :key="item.OrderID"
              :label="item.OrderID"
              :value="item.OrderID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物流商" prop="VendorID" label-width="150px">
          <el-select v-model="addOrderForm.VendorID" placeholder="请选择物流商">
            <el-option
              v-for="item in vendorIDList"
              :key="item.VendorID"
              :label="item.VendorName"
              :value="item.VendorID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收货地址" prop="Address" label-width="150px">
          <el-input v-model="addOrderForm.Address" autocomplete="off" />
        </el-form-item>
        <el-form-item label="收货名" prop="Consignee" label-width="150px">
          <el-input v-model="addOrderForm.Consignee" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系电话" prop="Telephone" label-width="150px">
          <el-input v-model="addOrderForm.Telephone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="物流商订单备注" prop="Remarks" label-width="150px">
          <el-input v-model="addOrderForm.Remarks" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addOrderFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddOrdersForm(addOrderFormRef)"> 添加 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑物流商订单 -->
    <el-dialog v-model="editOrderFormVisible" title="编辑物流商订单" width="800">
      <el-form :model="editOrderForm" ref="editOrderFormRef" :rules="orderFormRules">
        <el-form-item label="商品订单ID" prop="OrderID" label-width="150px">
          <el-input v-model="editOrderForm.OrderID" placeholder="请选择商品订单ID" disabled />
        </el-form-item>
        <el-form-item label="物流商ID" prop="VendorID" label-width="150px">
          <el-input v-model="editOrderForm.VendorID" placeholder="请选择物流商" disabled />
        </el-form-item>
        <el-form-item label="收货地址" prop="Address" label-width="150px">
          <el-input v-model="editOrderForm.Address" autocomplete="off" />
        </el-form-item>
        <el-form-item label="收货名" prop="Consignee" label-width="150px">
          <el-input v-model="editOrderForm.Consignee" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系电话" prop="Telephone" label-width="150px">
          <el-input v-model="editOrderForm.Telephone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="物流商订单备注" prop="Remarks" label-width="150px">
          <el-input v-model="editOrderForm.Remarks" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editOrderFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditOrdersForm(editOrderFormRef)">
            编辑
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看物流商订单 -->
    <el-dialog v-model="checkOrderFormVisible" title="查看物流商订单" width="800">
      <h1 style="margin-bottom: 16px">订单 {{ orderInfo.LogisticsID }} 状态</h1>
      <el-steps
        style="max-width: 800px; height: 500px"
        :active="orderInfo.Node.length"
        direction="vertical"
      >
        <el-step
          v-for="item in orderInfo.Node"
          :title="item.update_time + '-' + item.data"
          :key="item.data"
        />
      </el-steps>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checkOrderFormVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
#orders {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 16px 32px;
  box-sizing: border-box;

  .options-row {
    margin-bottom: 16px;
  }

  .options,
  .search,
  .add {
    width: 100%;
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .search {
    .search-button {
      padding: 0 32px;
      margin-left: 16px;
    }
  }

  .add {
    .add-button {
      padding: 0 48px;
    }
  }

  .page {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 32px;
  }
}
</style>
